import Req from '@/api/user'
import {isEmpty} from '@/utils/util'
import dayjs from 'dayjs'
import CryptoJS from "crypto-js";

export default {
  name: 'UserManagement',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    // 邮箱验证规则
    const validateEmail = (rule, value, callback) => {
      if (value && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(value)) {
        callback(new Error('请输入正确的邮箱地址'))
      } else {
        callback()
      }
    }

    return {
      // 搜索表单
      searchForm: {
        username: '',
        mobile: '',
        pageNum: 1,
        pageSize: 10
      },
      // 表格数据
      tableData: [],
      loading: false,
      // 选中的用户
      selectedUsers: [],
      // 分页信息
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 对话框
      dialogVisible: false,
      dialogTitle: '新增用户',
      submitLoading: false,
      // 表单数据
      formData: {
        userId: '',
        userName: '',
        password: '',
        // realName: '',
        mobile: '',
        email: '',
        gender: '',
        roleId: '',
        // status: 1
      },
      // 表单验证规则
      formRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
        ],
        realName: [
          {required: true, message: '请输入真实姓名', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {validator: validatePhone, trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {validator: validateEmail, trigger: 'blur'}
        ],
        role: [
          {required: true, message: '请选择角色', trigger: 'change'}
        ]
      },
      roleList: [],
      roleParam: {
        roleName: '',
        status: '',
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.getList()
      this.getRoleList()
    },
    // 获取用户列表
    getList() {
      Req.getUserList(this.searchForm).then(res => {
        this.tableData = res.data.list
        this.pagination.total = res.data.total
      })
    },
    // async getList() {
    //   this.loading = true
    //   try {
    //     // 模拟接口调用
    //     await new Promise(resolve => setTimeout(resolve, 500))
    //     this.tableData = [
    //       {
    //         id: 1,
    //         username: 'admin',
    //         realName: '管理员',
    //         phone: '13800138000',
    //         email: 'admin@example.com',
    //         role: 'admin',
    //         status: 1,
    //         createTime: '2024-01-01 12:00:00'
    //       }
    //       // ... 更多数据
    //     ]
    //     this.pagination.total = 100
    //   } catch (error) {
    //     this.$message.error('获取用户列表失败')
    //   } finally {
    //     this.loading = false
    //   }
    // },
    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1
      this.getList()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        username: '',
        realName: '',
        status: ''
      }
      this.handleSearch()
    },
    // 新增用户
    handleAdd() {
      this.dialogTitle = '新增用户'
      this.formData = {
        id: '',
        username: '',
        password: '',
        realName: '',
        phone: '',
        email: '',
        role: 'user',
        status: 1
      }
      this.dialogVisible = true
    },
    // 编辑用户
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.formData = {...row}
      this.dialogVisible = true
    },
    // 删除用户
    handleDelete(row) {
      this.$confirm('确认删除该用户?', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          // 调用删除接口
          await new Promise(resolve => setTimeout(resolve, 500))
          this.$message.success('删除成功')
          this.getList()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {
      })
    },
    // 批量删除
    handleBatchDelete() {
      this.$confirm(`确认删除选中的 ${this.selectedUsers.length} 个用户?`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          // 调用批量删除接口
          await new Promise(resolve => setTimeout(resolve, 500))
          this.$message.success('删除成功')
          this.getList()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {
      })
    },
    // 提交表单
    handleSubmit() {
      this.$refs.userForm.validate(async valid => {
        if (!valid) return

        this.submitLoading = true
        try {
          this.formData.password = CryptoJS.MD5(this.formData.password).toString()

          Req.createUser(this.formData).then(res => {
            this.$message.success(this.formData.userId ? '修改成功' : '新增成功')
          }).finally(() => {
            this.getList()
            this.dialogVisible = false
          })

        } catch (error) {
          this.$message.error(this.formData.userId ? '修改失败' : '新增失败')
        } finally {
          this.submitLoading = false
        }
      })
    },
    // 状态变更
    async handleStatusChange(row) {
      try {
        // 调用状态变更接口
        await new Promise(resolve => setTimeout(resolve, 500))
        this.$message.success('状态修改成功')
      } catch (error) {
        row.status = row.status === 1 ? 0 : 1
        this.$message.error('状态修改失败')
      }
    },
    // 选择变更
    handleSelectionChange(selection) {
      this.selectedUsers = selection
    },
    // 每页大小变更
    handleSizeChange(val) {
      this.searchForm.pageSize = this.pagination.pageSize = val
      this.getList()
    },
    // 页码变更
    handleCurrentChange(val) {
      this.searchForm.pageNum = this.pagination.currentPage = val
      this.getList()
    },
    // 关闭对话框
    handleDialogClose() {
      this.$refs.userForm && this.$refs.userForm.resetFields()
    },
    getRoleList() {
      Req.getRoleList(this.roleParam).then(res => {
        this.roleList = res.data.list
      })
    }
    // formatDate(date) {
    //   const options = { year: 'numeric', month: 'long', day: 'numeric' };
    //   return new Date(date).toLocaleDateString(undefined, options);
    // }
  }
}